interface CarState {
  car: CarItemState[];
}

interface CarItemState {
  title: string;
  id: string;
  url: string;
  price: number;
  desc: string;
  color: string;
  size: string;
  count: number;
  checked: boolean;
}

const ADD_CAR = "ADD_CAR";
const SUB_CAR_ITEM_COUNT = "SUB_CAR_ITEM_COUNT";
const ADD_CAR_ITEM_COUNT = "ADD_CAR_ITEM_COUNT";
const SWITCH_CAR_ITEM_CHECK = "SWITCH_CAR_ITEM_CHECK";
interface AddCarAction {
  type: typeof ADD_CAR;
  payload: CarItemState;
}
export const addCar = (payload: CarItemState): AddCarAction => {
  return { type: ADD_CAR, payload };
};

interface AddCarItemCountAction {
  type: typeof ADD_CAR_ITEM_COUNT;
  payload: string;
}

export const addCarItemCount = (payload: string): AddCarItemCountAction => {
  return { type: ADD_CAR_ITEM_COUNT, payload };
};

interface SubCarItemCountAction {
  type: typeof SUB_CAR_ITEM_COUNT;
  payload: string;
}

export const subCarItemCount = (payload: string): SubCarItemCountAction => {
  return { type: SUB_CAR_ITEM_COUNT, payload };
};

interface SwitchCarItemCheckAction {
  type: typeof SWITCH_CAR_ITEM_CHECK;
  payload: string;
}

export const switchCarItemCheck = (
  payload: string
): SwitchCarItemCheckAction => {
  return { type: SWITCH_CAR_ITEM_CHECK, payload };
};

type CarAction =
  | AddCarAction
  | AddCarItemCountAction
  | SubCarItemCountAction
  | SwitchCarItemCheckAction;
const initState: CarState = {
  car: JSON.parse(localStorage.getItem("car") || "[]"),
};

export default (state = initState, action: CarAction) => {
  switch (action.type) {
    case ADD_CAR: {
      const result = state.car.find((v) => {
        return v.id === action.payload.id;
      });

      if (result) {
        result.count++;
      } else {
        state.car.unshift({ ...action.payload });
      }

      return {
        ...state,
        car: [...state.car],
      };
    }
    case ADD_CAR_ITEM_COUNT: {
      const result = state.car.find((v) => v.id === action.payload);
      if (result) result.count++;
      return {
        ...state,
        car: [...state.car],
      };
    }
    case SUB_CAR_ITEM_COUNT: {
      const result = state.car.find((v) => v.id === action.payload);
      if (result) result.count--;
      return {
        ...state,
        car: [...state.car],
      };
    };
    case SWITCH_CAR_ITEM_CHECK: {
      const result = state.car.find((v) => v.id === action.payload);
      if (result) result.checked = !result.checked;
      return {
        ...state,
        car: [...state.car],
      };
    }
    default:
      return state;
  }
};
